﻿'''
msgbus module
'''
import PyQt4.QtCore.QThread
import PyQt4.QtCore.pyqtSignal

import multiprocess
import socket
#import Unpickler

import gcm #orz global component mananger
import dht

#multiprocessing.Manager() 

class msgbus(object):
    def __init__(self):
        self.qlist={}
        self.qlist['lazy'] = multiprocessing.Queue(512*1024)
        # put lazy data in here, like file transfer and localIO
        self.qlist['normal'] = multiprocessing.Queue(256*1024)
        # put mormal data in here like IM, wiki, mail, search request
        self.qlist['first'] = multiprocessing.Queue(128*1024)
        # put first data in here, like respond, realtime game and AV
        m = gcm.manager()
    
    def put(self, item, priority):
        try:
            self.qlist[priority].put_nowait(item)
        except:
            print 'Queue.put_nowait() error'
                
    def get(self, priority):
        try:
            comid, data = self.qlist[priority].get_nowait()
        except:
            print 'Queue_first.get_nowait() error'
        else:
            m.getcom(comid).invoke(data)
    
class orznic(object):
    def __init__(self, port = 4661):
        self.host = socket.gethostbyname(socket.gethostname())
        self.port = port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.s.setblocking(0)
        self.s.bind((host, port))
        
    def recv(self):
        try:
            item = self.s.recv(1024)
        except socket.error:
            print 'socket.recv() error'
        else:
            if validate(item):
                msgbus.put(unpack(item), 'first')
                
    def send(self, priority = None):
        try:
            item, (addr, port) = msgbus.get('first')
        except socket.error:
            print 'q_first.get_nowait() error'
        self.s.sendto(item, (addr, port)) 
        
    def validate(self, item):
        # do somthing work to validate item
        if item == 'welcome to orzp2p':
            return True
        return False
        